<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { saveGroup, getGroupById, selectParentGroups } from '@/api/system/authority'
import { useEmitt } from '@/hooks/web/useEmitt'
import { ElMessageBox } from 'element-plus'
import { Check, Close } from '@element-plus/icons-vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useCache } from '@/hooks/web/useCache'
import { useLocaleStore } from '@/store/modules/locale'
import { getZhHKAndPinyin, getZhCNAndPinyin } from '@/api/common'

defineOptions({
  name: 'GroupAdd'
})

const localeStore = useLocaleStore()

const { t } = useI18n()
const { emitter } = useEmitt()
const formRef = ref()
const { currentRoute } = useRouter()
const { wsCache } = useCache()

const state = reactive({
  // 表单数据
  formData: {
    groupId: '',
    groupName: '',
    hkName: '',
    enName: '',
    sort: 1,
    parentId: '',
    remark: '',
    status: 1,
    groupType: 0,
    seq: 1
  },
  parentGroupList: [{}],
  parentName: 'groupName',
  groupTypeList: [{}],
  // 校验规则
  formRules: {
    groupName: [
      {
        required: true,
        message: t('group.iptGroupName'),
        trigger: ['blur', 'change']
      },
      {
        pattern: '[^ \x22]+',
        message: t('company.emptyMsg'),
        trigger: ['blur', 'change']
      }
    ],
    status: { required: true, message: t('group.errStatusEmpty'), trigger: 'blur' }
  },
  // 狀態options
  statusOptions: [
    {
      value: 1,
      label: t('group.activated')
    },
    {
      value: 0,
      label: t('group.disabled')
    }
  ],
  loading: false
})
onMounted(async () => {
  init()
})

// 保存表单
const save = () => {
  formRef.value.validate(async (vaild) => {
    if (!vaild) {
      return
    }
    let form = Object.assign({}, state.formData)

    state.loading = true
    let type = 'add'
    if (form.groupId) {
      type = 'edit'
    }
    await saveGroup(form).then((res) => {
      const result = res as any
      //保存成功
      if (result.success) {
        //刷新列表
        emitter.emit('refreshList', type)
        goBack()
      } else {
        ElMessageBox.alert(t(result.message))
      }
      state.loading = false
    })
  })
}
// 返回列表
const goBack = () => {
  emitter.emit('closeTag', {
    closePath: currentRoute.value.fullPath,
    backPath: '/System/GroupList'
  })
}
/**
 * @description 当繁体中文为空时，转换简体中文为繁体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhHKAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //繁体中文为空时才自动转换
  if (state.formData.hkName.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  state.formData.hkName = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
}

/**
 * @description 当简体中文为空时，转换繁体中文为简体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhCNAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //简体中文为空时才自动转换
  if (state.formData.groupName.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  state.formData.groupName = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
}

//刷新父节点
const refreshParent = async () => {
  await selectParentGroups(state.formData.groupId, state.formData.groupType)
    .then((res) => {
      const result = res as any
      state.parentGroupList = result.data
    })
    .catch(() => {})
}
//渲染页面的接口
const init = async () => {
  const groupId = wsCache.get('curGroup')?.groupId
  //修改
  if (groupId) {
    const data = (await getGroupById(groupId)) as any
    state.formData = data.data
  }
  refreshParent()
  //当前语言
  var curLang = localeStore.getCurrentLocale.lang
  if (curLang == 'en') {
    state.parentName = 'enName'
  } else if (curLang == 'zh_HK') {
    state.parentName = 'hkName'
  }
  state.groupTypeList.push({ id: 0, name: t('group.groupType0') })
  state.groupTypeList.push({ id: 1, name: t('group.groupType1') })
  state.groupTypeList.push({ id: 2, name: t('group.groupType2') })
  state.groupTypeList.push({ id: 4, name: t('group.groupType4') })
  state.groupTypeList.push({ id: 8, name: t('group.groupType8') })
}
</script>

<template>
  <div>
    <!-- 卡片表頭 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ $t('group.groupInfo') }}</span>
        </div>
      </template>
      <el-form
        ref="formRef"
        :model="state.formData"
        :rules="state.formRules"
        class="demo-form-inline"
        label-position="left"
        label-width="150px"
        style="padding-right: 40px; padding-top: 10px"
      >
        <el-row :gutter="40">
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('group.groupName')" prop="groupName">
              <el-input
                v-model="state.formData.groupName"
                :placeholder="$t('group.iptGroupName')"
                maxlength="50"
                show-word-limit
                @blur="zhHKAndPinyin($event)"
              />
            </el-form-item>
            <el-form-item :label="$t('common.hkName')" prop="hkName">
              <el-input
                v-model="state.formData.hkName"
                :placeholder="$t('common.inputText') + $t('common.hkName')"
                maxlength="50"
                show-word-limit
                @blur="zhCNAndPinyin($event)"
              />
            </el-form-item>
            <el-form-item :label="$t('common.enName')" prop="enName">
              <el-input
                v-model="state.formData.enName"
                :placeholder="$t('common.inputText') + $t('common.enName')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('common.status')" prop="status">
              <el-select
                v-model="state.formData.status"
                :placeholder="$t('common.selectText')"
                size="default"
              >
                <el-option
                  v-for="item in state.statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('group.groupType')" prop="groupType">
              <el-select
                v-model="state.formData.groupType"
                :placeholder="$t('common.selectText')"
                size="default"
                @change="refreshParent"
              >
                <el-option
                  v-for="item in state.groupTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('common.parentName')" prop="parentId">
              <el-select
                v-model="state.formData.parentId"
                :placeholder="$t('common.selectText')"
                size="default"
              >
                <el-option
                  v-for="item in state.parentGroupList"
                  :key="item.groupId"
                  :label="item[state.parentName]"
                  :value="item.groupId"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('common.sort')" prop="sort">
              <el-input-number
                :min="1"
                :max="999999"
                :step="10"
                v-model="state.formData.sort"
                :placeholder="$t('common.inputText') + $t('common.sort')"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item :label="$t('common.remark')" prop="remark">
              <el-input
                v-model="state.formData.remark"
                :placeholder="$t('common.iptRemarks')"
                type="textarea"
                :autosize="{ minRows: 2 }"
                maxlength="255"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="detailFooter">
        <el-button type="primary" plain @click="save" :loading="state.loading">
          <el-icon><Check /></el-icon>&nbsp;{{ $t('common.save') }}
        </el-button>
        <el-button type="info" plain @click="goBack">
          <el-icon><Close /></el-icon>&nbsp;{{ $t('common.giveUp') }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>
<style lang="less" scoped>
.box-card {
  .card-header {
    font-size: 16px;
    letter-spacing: 1px;
  }
  :deep(.el-input) {
    font-size: 12px;
  }
  :deep(.el-textarea__inner) {
    height: 85px;
    font-size: 12px;
  }
}
:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
}
.el-select-dropdown__item {
  font-size: 12px;
}
</style>
